package com.youhome.controller;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.youhome.model.User;
import com.youhome.model.UserLoginInfo;
import com.youhome.model.WXSession;
import com.youhome.response.Result;
import com.youhome.response.ResultCode;
import com.youhome.service.TokenService;
import com.youhome.service.UserService;
import com.youhome.utils.HttpClientUtils;
import com.youhome.utils.TokenUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by chen365 on 2018/12/06.
 */
@RestController
@RequestMapping(value = "/wx")
@Api(tags = "微信")
@Slf4j
public class WXController {

    @Value("${wx.appId}")
    private String appId;

    @Value("${wx.appSecret}")
    private String appSecret;

    @Value("${wx.grantType}")
    private String grantType;

    @Value("${wx.requestUrl}")
    private String requestUrl;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private UserService userService;

    @ApiOperation(value = "微信授权", notes = "微信授权", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "code", value = "code", required = true, paramType = "query")
    })
    @PostMapping(value = "/login")
    public Object login(String code) {
        log.error("code: {}", code);
        String url = this.requestUrl + "?appid=" + appId + "&secret=" + appSecret + "&js_code=" + code + "&grant_type=" + grantType;
        // 发送请求
        JSONObject jsonObject = HttpClientUtils.httpGet(url);
        log.debug("请求地址：{}", url);
        log.debug("请求结果：{}", jsonObject);

        if (jsonObject.getString("errcode") == null) {
            ObjectMapper mapper = new ObjectMapper();
            try {
                WXSession wxSession = mapper.readValue(jsonObject.toJSONString(), WXSession.class);
                String token = tokenService.createToken(wxSession);
                UserLoginInfo info = new UserLoginInfo();

                info.setToken(token);
                String openid = wxSession.getOpenid();
                User currentUser = userService.getCurrentUser(openid);
                if (currentUser != null) {
                    String phone = currentUser.getPhone();
                    if (!StringUtils.isEmpty(phone)) {
                        info.setPhone(phone);
                        info.setIsSignIn(true);
                    }
                }

                return new Result<>(ResultCode.SUCCESS, info);
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return new Result<>(ResultCode.FAIL);
    }
}
